<template>
  <!-- 弹框 -->
  <el-dialog :visible.sync="dialogShow" :title="title" width="40%" @close="onClose">
    <!-- 表单区域 -->
    <el-form
      ref="form"
      label-width="140px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="角色名称" prop="role_name">
        <el-input v-model="formData.role_name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色标识" prop="identify">
        <el-input v-model="formData.identify" placeholder="请输入角色标识" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入角色描述"
        />
      </el-form-item>
      <!-- :check-strictly="true"  父子不关联 -->
      <el-form-item label="角色权限" prop="authlist">
        <el-tree
          ref="tree"
          node-key="id"
          :data="treelist"
          :props="{ label: 'permission_name' }"
          show-checkbox
          :default-checked-keys="defaultCheck"
          @check="getTreeId"
        />
      </el-form-item>
      <el-row type="flex" justify="end">
        <el-button size="small" @click="dialogShow = false">取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="onSubmit"
        >确定</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import { addRole, editRole, getRoleList } from '@/api/role'
import { getmenuLits } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'
export default {
  name: 'AddRole',
  data() {
    // 校验名字是否重复
    const roleName = async(rule, value, callback) => {
      const { list } = await getRoleList()
      // console.log(list)
      const arr = list.filter((item) => {
        return item.role_name === value && item.role_name !== ''
      })
      console.log(arr)
      if (this.formData.id) {
        // const add = list.some(item => item.role_name === value)
        if (list.some(item => item.role_name === value)) {
          callback()
        }
      } else {
        arr.length > 0 ? callback(new Error(`已经存在${value}名称`)) : callback()
      }
    }
    // 校验标识是否重复
    const identify = async(rule, value, callback) => {
      const { list } = await getRoleList()
      // console.log(list)
      const arr = list.filter((item) => {
        return item.identify === value && item.identify !== ''
      })
      // console.log(arr)
      if (this.formData.id) {
        // const add = list.some(item => item.role_name === value)
        if (list.some(item => item.identify === value)) {
          callback()
        }
      } else {
        arr.length > 0 ? callback(new Error(`已经存在${value}标识`)) : callback()
      }
    }
    // 校验是否选中数
    // const roleTree = (rule, value, callback) => {
    //   if (this.formData.authlist.length === 0) {
    //     callback(new Error('请输入菜单权限'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      defaultCheck: [], // 默认勾选的节点
      // 树形结构
      treelist: [],
      // 弹框控制变量
      dialogShow: false,
      // 表单数据变量
      formData: {
        authlist: [],
        description: '',
        identify: '',
        role_name: ''
      },
      // 表单验证规则
      formRules: {
        authlist: [
          { type: 'array', required: true, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        identify: [
          { required: true, message: '请输入标识', trigger: 'blur' },
          { validator: identify, trigger: 'blur' }
        ],
        role_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: roleName }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改角色' : '添加角色'
    }
  },
  created() {
    this.initDept()
  },
  methods: {
    // 回显已勾选数据
    getcheck(arr) {
      this.defaultCheck = arr
    },
    getTreeId() {
      // 获取半选中父亲id
      const parent = this.$refs.tree.getCheckedKeys()
      // 获取选中id(父子默认关联了)
      const son = this.$refs.tree.getHalfCheckedKeys()
      // 赋值
      this.formData.authlist = [...parent, ...son]
    },
    // 获取树
    async initDept() {
      const res = await getmenuLits()
      // console.log(res)
      this.treelist = tranListToTreeData(res, 0)
    },
    // 提交行为
    async onSubmit() {
      // this.formData.authlist = this.$refs.tree.getCheckedKeys()
      // 表单的校验
      // console.log(this.formData)
      if (this.formData.authlist.length === 0) return this.$message.warning('请选择菜单权限')
      await this.$refs.form.validate()
      // 加工处理表单数据(拷贝一份再加工)
      // 请求的发生
      if (this.formData.id) {
        if (this.formData.id === 29) {
          return this.$message.error('超级管理员不允许修改')
        } else {
          await editRole(this.formData)
        }
      } else {
        await addRole(this.formData)
      }

      // 提示效果
      this.$message.success(this.formData.id ? '修改成功' : '添加成功')
      // 关闭弹框
      this.dialogShow = false
      // 列表更新
      this.$emit('updateList')
    },
    // 弹框关闭
    onClose() {
      // 表单重置
      this.formData = {
        authlist: [],
        description: '',
        identify: '',
        role_name: ''
      }
      this.defaultCheck = []
      // 清除勾选状态
      this.$refs.tree.setCheckedKeys([])
      // 移除校验
      this.$refs.form.clearValidate()
    }
  }
}
</script>
<style scoped></style>
